@model List<CaipuGuanliXitong.Models.CookBook>

@{
    ViewData["Title"] = "菜谱管理";
}

<h2>菜谱管理</h2>

@if (ViewBag.Message != null)
{
    <div class="alert @(ViewBag.IsSuccess ? "alert-success" : "alert-danger")">
        @ViewBag.Message
    </div>
}

<div class="row mb-3">
    <div class="col-md-6">
        <a asp-action="Create" class="btn btn-primary">新增菜谱</a>
        <a asp-action="ExportToExcel" class="btn btn-success">导出Excel</a>
        <button type="button" class="btn btn-danger" id="batchDeleteBtn" style="display:none;" onclick="confirmBatchDelete()">批量删除</button>
    </div>
    <div class="col-md-6">
        <form asp-action="ImportFromExcel" method="post" enctype="multipart/form-data" class="form-inline justify-content-end">
            <div class="form-group">
                <input type="file" name="file" class="form-control-file" accept=".xlsx,.xls" />
            </div>
            <button type="submit" class="btn btn-info ml-2">导入Excel</button>
        </form>
    </div>
</div>

<form asp-action="Index" method="get">
    <div class="form-actions no-color">
        <p>
            搜索: <input type="text" name="SearchString" value="@ViewBag.CurrentFilter" />
            <input type="submit" value="搜索" class="btn btn-default" /> |
            <a asp-action="Index">返回完整列表</a>
        </p>
    </div>
</form>

<table class="table">
    <thead>
        <tr>
            <th>
                <input type="checkbox" id="selectAll" />
            </th>
            <th>
                <a asp-action="Index" asp-route-sortOrder="@ViewBag.NameSortParm" asp-route-currentFilter="@ViewBag.CurrentFilter">菜谱名称</a>
            </th>
            <th>
                <a asp-action="Index" asp-route-sortOrder="@ViewBag.CategorySortParm" asp-route-currentFilter="@ViewBag.CurrentFilter">分类</a>
            </th>
            <th>
                <a asp-action="Index" asp-route-sortOrder="@ViewBag.DateSortParm" asp-route-currentFilter="@ViewBag.CurrentFilter">创建时间</a>
            </th>
            <th>
                <a asp-action="Index" asp-route-sortOrder="@ViewBag.DateSortParm" asp-route-currentFilter="@ViewBag.CurrentFilter">修改时间</a>
            </th>
            <th>操作</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    <input type="checkbox" class="cookbook-checkbox" value="@item.Id" />
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Name)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Category)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.CreatedTime)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.UpdatedTime)
                </td>
                <td>
                    <a asp-action="Edit" asp-route-id="@item.Id" class="btn btn-info btn-sm">编辑</a>
                    <a asp-action="Details" asp-route-id="@item.Id" class="btn btn-success btn-sm">详情</a>
                    <button type="button" class="btn btn-danger btn-sm" onclick="confirmDelete('@item.Id', '@item.Name')">删除</button>
                </td>
            </tr>
        }
    </tbody>
</table>

<div>
    @{
        var totalItems = ViewBag.TotalItems != null ? (int)ViewBag.TotalItems : Model.Count();
        var currentPage = ViewBag.CurrentPage != null ? (int)ViewBag.CurrentPage : 1;
        var pageSize = ViewBag.PageSize != null ? (int)ViewBag.PageSize : 10;
        var totalPages = (int)Math.Ceiling((double)totalItems / pageSize);

        if (totalPages > 1)
        {
            <nav aria-label="Page navigation">
                <ul class="pagination pagination-lg">
                    @if (currentPage > 1)
                    {
                        <li class="page-item">
                            <a class="page-link" asp-action="Index" asp-route-page="@(currentPage - 1)" asp-route-currentFilter="@ViewBag.CurrentFilter" asp-route-sortOrder="@ViewBag.CurrentSort" aria-label="Previous">
                                <span aria-hidden="true">&laquo;</span>
                                <span class="sr-only">上一页</span>
                            </a>
                        </li>
                    }

                    @for (var i = 1; i <= totalPages; i++)
                    {
                        <li class="page-item @(i == currentPage ? "active" : "")">
                            <a class="page-link" asp-action="Index" asp-route-page="@i" asp-route-currentFilter="@ViewBag.CurrentFilter" asp-route-sortOrder="@ViewBag.CurrentSort">@i</a>
                        </li>
                    }

                    @if (currentPage < totalPages)
                    {
                        <li class="page-item">
                            <a class="page-link" asp-action="Index" asp-route-page="@(currentPage + 1)" asp-route-currentFilter="@ViewBag.CurrentFilter" asp-route-sortOrder="@ViewBag.CurrentSort" aria-label="Next">
                                <span aria-hidden="true">&raquo;</span>
                                <span class="sr-only">下一页</span>
                            </a>
                        </li>
                    }
                </ul>
            </nav>
        }
    }
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteModalLabel">确认删除</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>您确定要删除菜谱 <strong id="cookBookName"></strong> 吗？</p>
                <p class="text-danger">此操作不可撤销！</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <form id="deleteForm" asp-action="Delete" method="post" style="display:inline;">
                    <input type="hidden" name="id" id="cookBookId" />
                    <button type="submit" class="btn btn-danger">确认删除</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 批量删除确认模态框 -->
<div class="modal fade" id="batchDeleteModal" tabindex="-1" role="dialog" aria-labelledby="batchDeleteModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="batchDeleteModalLabel">确认批量删除</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>您确定要删除选中的 <strong id="selectedCount">0</strong> 个菜谱吗？</p>
                <p class="text-danger">此操作不可撤销！</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" onclick="performBatchDelete()">确认删除</button>
            </div>
        </div>
    </div>
</div>

@section Scripts {
    <script>
        // 全选/取消全选功能
        document.getElementById('selectAll').addEventListener('change', function () {
            const checkboxes = document.querySelectorAll('.cookbook-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
            });
            toggleBatchDeleteButton();
        });

        // 单个复选框状态改变时，更新全选状态和批量删除按钮
        document.querySelectorAll('.cookbook-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', function () {
                const allCheckboxes = document.querySelectorAll('.cookbook-checkbox');
                const allChecked = Array.from(allCheckboxes).every(cb => cb.checked);
                document.getElementById('selectAll').checked = allChecked;
                toggleBatchDeleteButton();
            });
        });

        // 显示/隐藏批量删除按钮
        function toggleBatchDeleteButton() {
            const selectedCount = getSelectedCookbookIds().length;
            const batchDeleteBtn = document.getElementById('batchDeleteBtn');
            batchDeleteBtn.style.display = selectedCount > 0 ? 'inline-block' : 'none';
        }

        // 获取选中的菜谱ID
        function getSelectedCookbookIds() {
            const checkboxes = document.querySelectorAll('.cookbook-checkbox:checked');
            return Array.from(checkboxes).map(cb => cb.value);
        }

        // 确认批量删除
        function confirmBatchDelete() {
            const selectedIds = getSelectedCookbookIds();
            document.getElementById('selectedCount').textContent = selectedIds.length;
            $('#batchDeleteModal').modal('show');
        }

        // 执行批量删除
        function performBatchDelete() {
            const selectedIds = getSelectedCookbookIds();
            if (selectedIds.length === 0) return;

            // 创建表单并提交
            const form = document.createElement('form');
            form.method = 'post';
            form.action = '@Url.Action("BatchDelete", "CookBook")';

            // 添加防伪令牌
            const token = document.querySelector('input[name="__RequestVerificationToken"]');
            if (token) {
                const tokenInput = document.createElement('input');
                tokenInput.type = 'hidden';
                tokenInput.name = '__RequestVerificationToken';
                tokenInput.value = token.value;
                form.appendChild(tokenInput);
            }

            // 添加选中的ID
            selectedIds.forEach(id => {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'ids';
                input.value = id;
                form.appendChild(input);
            });

            document.body.appendChild(form);
            form.submit();
        }

        // 单个删除确认
        function confirmDelete(id, name) {
            document.getElementById('cookBookId').value = id;
            document.getElementById('cookBookName').innerText = name;
            $('#deleteModal').modal('show');
        }
    </script>
}